<template>
  <el-select
    v-model="selectedCustomerId"
    filterable
    remote
    :remote-method="handleSearch"
    :loading="loading"
    placeholder="请选择客户"
    clearable
    @change="handleChange"
  >
    <el-option
      v-for="item in customerOptions"
      :key="item.id"
      :label="item.customerName"
      :value="item.id"
    >
      <span>{{ item.customerName }}</span>
      <span class="text-gray-400 ml-2">{{ item.contactName }}</span>
    </el-option>
  </el-select>
</template>

<script setup lang="ts">
import { CustomerApi, CustomerVO } from '@/api/oa/customer'

defineOptions({ name: 'CustomerSelect' })

const props = defineProps<{
  modelValue?: number
}>()

const emit = defineEmits(['update:modelValue', 'change'])

const loading = ref(false)
const customerOptions = ref<CustomerVO[]>([])
const selectedCustomerId = ref(props.modelValue)

// 初始化加载数据
const initData = async () => {
  loading.value = true
  try {
    const res = await CustomerApi.getCustomerPage({
      pageNo: 1,
      pageSize: 10
    })
    customerOptions.value = res.list
  } finally {
    loading.value = false
  }
}

// 监听值变化
watch(() => props.modelValue, (val) => {
  selectedCustomerId.value = val
})

// 搜索客户
const handleSearch = async (query: string) => {
  loading.value = true
  try {
    const res = await CustomerApi.getCustomerPage({
      pageNo: 1,
      pageSize: 10,
      customerName: query
    })
    customerOptions.value = res.list
  } finally {
    loading.value = false
  }
}

// 选择客户
const handleChange = (value: number) => {
  emit('update:modelValue', value)
  const selected = customerOptions.value.find(item => item.id === value)
  emit('change', selected)
}

// 组件挂载时加载数据
onMounted(() => {
  initData()
})
</script> 